package com.tanhua.gateway.filters;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一鉴权处理类
 * 1.如果前端发起是登录请求，直接放行
 * 2.如果前端发起的非登录请求，当前类进行鉴权处理，没有权限，直接返回
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter {
    //获取放行地址
    @Value("${gateway.excludedUrls}")
    private  List<String> excludedUrls;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 鉴权业务逻辑处理方法
     *
     * @param exchange 获取request respones
     * @param chain    继续执行后续流程对象
     * @return {@code Mono<Void>} to indicate when request processing is complete
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();//请求
        ServerHttpResponse response = exchange.getResponse();//响应
        //1获取地址
        log.debug("getURI****{}******getPath******{}*******getRemoteAddress*******{}********getQueryParams*********{}***********"
                , request.getURI(), request.getPath(), request.getRemoteAddress(),request.getQueryParams());
        RequestPath path = request.getPath();
        String requestPath = request.getURI().getPath();
        //2看一看是否与放行地址匹配，如果匹配就放行
        if (excludedUrls.contains(requestPath)){
            return chain.filter(exchange);
        }
        //3如果不是登录相关路径,获取请求头中token    headAuthorization: Bearer a.b.c
        String headAuthorization = request.getHeaders().getFirst("Authorization");
        if (!StringUtils.isEmpty(headAuthorization)) {
            //Bearer :后台管理系统-前端页面会带这个前缀
            String token = headAuthorization.replace("Bearer ", "");
            String tokenKey = "TOKEN_" + token;
            //4用redis查询是否存在 放行
            String userStr = stringRedisTemplate.opsForValue().get(tokenKey);
            if (!StringUtils.isEmpty(userStr)){
                return chain.filter(exchange);
            }
        }

        //5如果获取不到就返回
        log.error("***********用户未登录**********");
        //固定格式 响应式编程
        //8. 没值 401， 用户没有登录
        response.setStatusCode(HttpStatus.UNAUTHORIZED);//响应码 401 没权限
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);//响应数据json格式
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("errCode", 401);//响应码 401
        responseData.put("errMessage", "用户未登录");//响应数据json格式
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(responseData));
        return response.writeWith(Mono.just(dataBuffer));

    }
}
